﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Citiport.Util.IPGeo;

public partial class index : System.Web.UI.Page
{
    ctpDataContext db;
    public string imgstr1 = "v2img/1-0-1.jpg", imgstr2="v2img/9-148-0.jpg";
    public string imgurl1 = "city_s_show_picture.aspx?no=10", imgurl2 = "city_s_show_picture.aspx?no=278";

    string my_substring(string text)
    {
        int l=60;
        if (text.Length < l)
            return text;
        else
        {
            
            return text.Substring(0, l)+"...";
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        ctp_lib.check_user_language(this.Page);

        db = new ctpDataContext();

        if (!this.IsPostBack)
        {
           // displayLocalNews();
            this.mybind(0);
            this.DropDownList2.Visible = false;

            var mypic = from p in db.ct_s_picture_comments
                        join q in db.ct_s_pics on p.ct_s_no equals q.no
                        where q.ct_no==DateTime.Now.Second
                        orderby p.addtime descending
                        select new
                        {
                            filename = q.filename.Trim(),
                            tourl="city_s_show_picture.aspx?no="+q.no.ToString()
                        };

            
            mypic = mypic.Distinct().Take(2);

            

            int i = 0;
            foreach (var m in mypic)
            {
                if (i == 0)
                {
                    imgstr1 = "city_imgs/2/" + m.filename;
                    imgurl1 = m.tourl;
                    i++;
                }
                else if (i == 1)
                {
                    imgstr2 = "city_imgs/2/" + m.filename;
                    imgurl2 = m.tourl;
                    i++;
                }


            }
            

            if (this.Session["userno"] == null)
            {

                this.Panel2.Visible=false;

            }
            else
            {
                this.Panel1.Visible = false;
            
            }


            CountryLookup clookup = new CountryLookup(Server.MapPath("App_Data\\GeoIP.dat"));
            string local=clookup.lookupCountryName(this.Request.UserHostAddress).ToLower();

            if (local == "n/a")
                this.Label11.Text = "Citiport";
            else
            {
                this.Label11.Text = local;
            }

            ///

            GeoLingManager glManager = new GeoLingManager(Request, Response);
            String _lang = glManager.getLang();
            DatabaseUtil dbUtil = new DatabaseUtil();
            //Get user's preferred langugage in int
            _lang = dbUtil.getLanguageNo(_lang).ToString();


            var list3 = from p in db.ct_s_intros
                        join q in db.ct_s_profiles on p.ct_s_no equals q.no
                        where  q.valid == true
                        orderby p.addtime descending
                        select p.no;
            var list3_1 = from p in db.ct_s_intros
                          join q in db.ct_s_profiles on p.ct_s_no equals q.no
                          where  q.valid == true
                          orderby p.addtime descending
                          select q.no;
            var list3_2 = from p in db.ct_s_intros
                          join q in db.ct_s_profiles on p.ct_s_no equals q.no
                          join k in db.ct_profiles on q.ct_no equals k.no
                          where q.valid == true
                          orderby p.addtime descending
                          select k.no;
            Hashtable titlesTable = dbUtil.getTranlatePosts((int)DatabaseUtil.fromTables.s_profile_title, list3_1.Distinct().ToArray());
            Hashtable introsTable = dbUtil.getTranlatePosts((int)DatabaseUtil.fromTables.intro_intro, list3.Distinct().ToArray());
            Hashtable ctTitlesTable = dbUtil.getTranlatePosts((int)DatabaseUtil.fromTables.ct_profile_title, list3_2.Distinct().ToArray());
            var data3 = from p in db.ct_s_intros
                        join q in db.ct_s_profiles on p.ct_s_no equals q.no
                        join k in db.ct_profiles on q.ct_no equals k.no
                        where  q.valid == true && k.country==local
                        orderby p.addtime descending
                        select new
                        {
                            p.create_user_no,
                            intro = my_substring( dbUtil.getPropertyPost(p.intro, introsTable, p.no, _lang) ),

                            main_pic_fn = "city_imgs/1/" + q.main_pic_fn.Trim(),

                            country = k.country,
                            ct_title =dbUtil.getPropertyPost(k.title.Trim(), ctTitlesTable, k.no, _lang),

                             ct_url="city.aspx?no="+k.no.ToString(),

                            title = dbUtil.getPropertyPost(q.title.Trim(), titlesTable, q.no, _lang),
                            nickname = p.user.nickname.Trim(),
                            tourl = "city_s.aspx?no=" + p.ct_s_no.ToString()

                        };

            if (data3.Count() < 5)
            {
                data3 = from p in db.ct_s_intros
                            join q in db.ct_s_profiles on p.ct_s_no equals q.no
                            join k in db.ct_profiles on q.ct_no equals k.no
                            where q.valid == true
                            orderby p.addtime descending
                            select new
                            {
                                p.create_user_no,
                                intro = my_substring( dbUtil.getPropertyPost(p.intro, introsTable, p.no, _lang)),

                                main_pic_fn = "city_imgs/1/" + q.main_pic_fn.Trim(),

                                country = k.country,
                                ct_title = dbUtil.getPropertyPost(k.title.Trim(), ctTitlesTable, k.no, _lang),

                                ct_url = "city.aspx?no=" + k.no.ToString(),

                                title = dbUtil.getPropertyPost(q.title.Trim(), titlesTable, q.no, _lang),
                                nickname = p.user.nickname.Trim(),
                                tourl = "city_s.aspx?no=" + p.ct_s_no.ToString()

                            };

            }


            ////

            //var data3 = from p in db.ct_s_intros
            //            join q in db.ct_s_profiles on p.ct_s_no equals q.no
            //            join k in db.ct_profiles on q.ct_no equals k.no
            //            where  q.valid == true && k.country==local
            //            orderby p.addtime descending
            //            select new
            //            {
            //                p.create_user_no,
            //                p.intro,
                            
            //                country=k.country,
            //                ct_title=k.title.Trim(),

            //                main_pic_fn = "city_imgs/1/" + q.main_pic_fn.Trim(),

            //                title = q.title.Trim(),
            //                nickname = p.user.nickname.Trim(),
            //                tourl = "city_s.aspx?no=" + p.ct_s_no.ToString(),

            //                ct_url="city.aspx?no="+k.no.ToString()

            //            };

            //if(data3.Count()<5)
            //{

            //     data3 = from p in db.ct_s_intros
            //            join q in db.ct_s_profiles on p.ct_s_no equals q.no
            //            join k in db.ct_profiles on q.ct_no equals k.no
            //            where  q.valid == true
            //            orderby p.addtime descending
            //            select new
            //            {
            //                p.create_user_no,
            //                p.intro,
                            
            //                country=k.country,
            //                ct_title=k.title.Trim(),

            //                main_pic_fn = "city_imgs/1/" + q.main_pic_fn.Trim(),

            //                title = q.title.Trim(),
            //                nickname = p.user.nickname.Trim(),
            //                tourl = "city_s.aspx?no=" + p.ct_s_no.ToString(),

            //                ct_url="city.aspx?no="+k.no.ToString()

            //            };

            //}

            this.GridView3.DataSource = data3.Take(5);
            this.DataBind();


        } 
    }

    /// <summary>
    /// Display local news which location is determined by user's remote address
    /// </summary>
    //private void displayLocalNews()
    //{
    //    CountryLookup clookup = new CountryLookup(Server.MapPath("App_Data\\GeoIP.dat"));
    //    Due to the localhost, use a fake to test

    //    string local=clookup.lookupCountryName(this.Request.UserHostAddress);

    //    String local = clookup.lookupCountryName("12.25.205.51");
    //    String txt = "Hello! You are from " + local +"("+this.Request.UserHostAddress +")?";
    //    this.Literal_local_news.Text = txt;
    //}


    void mybind(int level)
    {
        //var cities = from p in db.ct_profiles
        //             where p.language_no == (int)Session["now_user_lang_no"]
        //             select p;

       // var hcities;

        var hcities = from p in db.ct_profiles 
                      //orderby p.ct_s_amount descending

                      select p;


        if (this.DropDownList1.SelectedIndex == 0)
        {
            //var taiwan_cities=from p in db.ct_profiles
            //                  where p.country=="taiwan" && p.no!=0
            //                  //orderby p.ct_s_amount descending
            //                  select p;
           // hcities = hcities.Except(taiwan_cities);

            hcities = from p in db.ct_profiles
                          where p.country != "taiwan" || p.no == 0
                          orderby p.ct_s_amount descending

                          select p;


        }

        #region dropbox
        if (level == 0)
        {
            if (this.DropDownList1.SelectedValue != "-1")
            {

                hcities = from p in db.ct_profiles
                              where p.continent == int.Parse(this.DropDownList1.SelectedValue)
                              orderby p.ct_s_amount descending

                              select p;

                //hcities = hcities.Where(p => p.continent == int.Parse(this.DropDownList1.SelectedValue));
                //cities = cities.Where(p => p.continent == int.Parse(this.DropDownList1.SelectedValue));

                this.DropDownList2.Visible = true;

                var contries = from p in hcities
                               select new
                               {
                                   p.country
                               };

                this.DropDownList2.DataSource = contries.Distinct();
                this.DropDownList2.DataTextField = "country";
                this.DropDownList2.DataValueField = "country";

            }
        }
        else
        {
            if (this.DropDownList2.SelectedItem != null)
            {
                if (this.DropDownList2.SelectedValue != "-1")
                {

                    hcities = from p in db.ct_profiles
                                  where p.country == this.DropDownList2.SelectedValue
                                  orderby p.ct_s_amount descending

                                  select p;

                    //hcities = hcities.Where(p => p.country == this.DropDownList2.SelectedValue);
                    //cities = cities.Where(p => p.country == this.DropDownList2.SelectedValue);


                }
            }

        }
        #endregion


        GeoLingManager glManager = new GeoLingManager(Request, Response);
        String _lang = glManager.getLang();
        DatabaseUtil dbUtil = new DatabaseUtil();
        //Get user's preferred langugage in int
        _lang = dbUtil.getLanguageNo(_lang).ToString();

        ArrayList al = new ArrayList();

        //foreach (ct_profile c in cities)
        //{
        //    if (c.ct_s_amount == 2)
        //        c.country = "citysize2";
        //    else if (c.ct_s_amount > 2 && c.ct_s_amount <= 5)
        //        c.country = "citysize3";
        //    else if (c.ct_s_amount > 5)
        //        c.country = "citysize4";
        //    else
        //        c.country = "citysize1";

        //    c.title = c.title.Trim();
        //    al.Add(c.no);
        //}

        //Hashtable citiesTable = dbUtil.getTranlatePosts((int)DatabaseUtil.fromTables.ct_profile_title, DataUtil.ObjsToInts(al.ToArray()));

        //foreach (ct_profile c in cities)
        //{
        //    c.title = dbUtil.getPropertyPost(c.title, citiesTable, c.no, _lang);
        //}


       // al = new ArrayList();
        foreach (ct_profile c in hcities)
        {
            if (c.main_pic_fn == null)
                c.main_pic_fn = "";
            else
                c.main_pic_fn = c.main_pic_fn.Trim();
            al.Add(c.no);
        }
        Hashtable hcitiesTable = dbUtil.getTranlatePosts((int)DatabaseUtil.fromTables.ct_profile_title, DataUtil.ObjsToInts(al.ToArray()));

        foreach (ct_profile c in hcities)
        {
            c.title = dbUtil.getPropertyPost(c.title, hcitiesTable, c.no, _lang);
        }

        this.DataList2.DataSource = hcities.Take(18);

        //this.DataList2.DataSource = hcities.Take(18).OrderByDescending(p=>p.ct_s_amount);

       // this.DataList1.DataSource = cities.Except(hcities.Take(14));

       // this.DataBind();
        //this.DataList1.DataBind();
        this.DataList2.DataBind();
        this.DropDownList2.DataBind();

        if (level == 0)
        {
            this.DropDownList2.Items.Add(new ListItem("Choose country", "-1"));
            this.DropDownList2.Items.FindByValue("-1").Selected = true;
        }
    }

    protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
    {
        this.mybind(0);
    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.mybind(1);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
 

        Response.Redirect("search.aspx?text=" + this.TextBox1.Text);
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        ctp_lib.check_login(this.Page, "my/index.aspx");
    }
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        this.Session.Remove("userno");
        Response.Redirect("index.aspx");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("login.aspx?id=" + this.TextBox2.Text + "&pwd=" + this.TextBox3.Text);
    }
}
